/**
 * 
 */
package idv.takeshi.software.productline.bookstore.application.service.spring;

import org.apache.commons.lang.Validate;
import org.h2.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import idv.takeshi.software.productline.bookstore.application.service.MaintainUserAccountService;
import idv.takeshi.software.productline.bookstore.application.service.OriginalPasswordInvalidException;
import idv.takeshi.software.productline.bookstore.domain.model.useraccount.UserAccount;
import idv.takeshi.software.productline.bookstore.domain.model.useraccount.UserAccountRepository;

/**
 * @author takeshi
 *
 */
@Service("maintainUserAccountService")
@Transactional
public class MaintainUserAccountServiceImpl implements
		MaintainUserAccountService {
	
	@Autowired
	private UserAccountRepository userAccountRepository;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	/* (non-Javadoc)
	 * @see idv.takeshi.software.productline.bookstore.application.service.MaintainUserAccountService#updateUserAccount(idv.takeshi.software.productline.bookstore.domain.model.useraccount.UserAccount, java.lang.String)
	 */
	public <T extends UserAccount> void updateUserAccount(T userAccount,
			String originalPassword) throws OriginalPasswordInvalidException {
		Validate.notNull(userAccount, "userAccount shall always not be null");
		Validate.notEmpty(originalPassword, "orginalPassword shall always not enull/empty");
		
		String encodedOriginalPassword = passwordEncoder.encodePassword(originalPassword, null);
		UserAccount tmpUserAccount = this.userAccountRepository.findById(userAccount.getId());
		
		if(!StringUtils.equals(tmpUserAccount.getPassword(), encodedOriginalPassword)){
			throw new OriginalPasswordInvalidException("user given original password:" + originalPassword +
					" is invalid");
		}
		
		userAccount.setPassword(originalPassword);
		
		String newEncodedPassword = this.passwordEncoder.encodePassword(userAccount.getOriginalPassword(), null);
		userAccount.setPassword(newEncodedPassword);
		
		this.userAccountRepository.update(userAccount);
	}

}
